A comprehensive lecture for BTech Computer Science students
A file is a named location on disk that stores related data permanently. Unlike variables, file data persists even after the program terminates.
Python handles both; today we focus on text files.
Forgetting to close a file can cause data corruption and resource leaks. Always close files â or better, use the with statement which closes automatically.
| Mode | Symbol | Description | File Exists? | File Missing? |
|---|---|---|---|---|
| Read | r | Read-only; file pointer at beginning | â Open | â Error |
| Write | w | Write-only; truncates existing content | â ī¸ Overwrite | â Create |
| Append | a | Write; appends to end of file | â Append | â Create |
| Read+Write | r+ | Read and write; no truncation | â Open | â Error |
| Write+Read | w+ | Read and write; truncates file | â ī¸ Overwrite | â Create |
| Binary Read | rb | Read binary file | â Open | â Error |
| Binary Write | wb | Write binary file | â ī¸ Overwrite | â Create |
| Method | Description | Returns |
|---|---|---|
| read(n) | Read n characters (or all if n omitted) | str |
| readline() | Read one line including \n | str |
| readlines() | Read all lines into a list | list |
| write(s) | Write string s to file | int (chars written) |
| writelines(lst) | Write list of strings | None |
| seek(pos) | Move file pointer to position | int |
| tell() | Return current file pointer position | int |
| flush() | Flush the write buffer | None |
| close() | Close the file | None |
An exception is an event that disrupts normal program flow during runtime. Unlike syntax errors (caught at compile time), exceptions occur during execution.
| Exception | Cause | Example |
|---|---|---|
| ZeroDivisionError | Division by zero | 10 / 0 |
| ValueError | Invalid value for operation | int("abc") |
| TypeError | Wrong data type used | "a" + 1 |
| FileNotFoundError | File does not exist | open("x.txt") |
| IndexError | List index out of range | lst[100] |
| KeyError | Dict key not found | d["x"] |
| NameError | Variable not defined | print(x) |
| AttributeError | Attribute not found | "hi".push() |
| ImportError | Module not found | import xyz |
| PermissionError | File access denied | open("/root/x") |
| MemoryError | Out of memory | [1]*10**10 |
| RecursionError | Max recursion depth exceeded | Infinite recursion |
Contains the code that might raise an exception. Python monitors this block. If an exception occurs, execution jumps to the matching except.
Handles the exception. You can have multiple except blocks for different exception types. Executed only when an exception matches.
Runs only when the try block completes successfully â no exception. Useful for code that should run only on success.
Always executes â whether an exception occurred or not. Use for cleanup tasks like closing files, releasing locks.
raise StatementUser-defined exceptions let you create meaningful, domain-specific errors. Always inherit from Exception (or its subclasses). This allows your exceptions to be caught by generic except Exception blocks.
CityName Population Area (space-separated)int("$") raises ValueError. 5//0 raises ZeroDivisionError. Handle both separately!FileNotFoundError to handle first run, file read/write, int/str conversion.